package com.aica.handler;


import com.aica.constant.ResultConstant;
import com.aica.constant.StringBuilderConstant;
import com.aica.service.MyUserDetailsService;
import com.aica.util.JwtTokenUtil;
import com.aica.util.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * 登出成功的处理类
 * @author by
 */
@Component
@Slf4j
public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {

        UsernamePasswordAuthenticationToken authentication1 = getAuthentication(httpServletRequest);
        SecurityContextHolder.getContext().setAuthentication(authentication1);

        Authentication authentication2 = SecurityContextHolder.getContext().getAuthentication();
        //已测试
        if(authentication2!=null){
            String name = authentication2.getName();


            if(!StringUtils.isEmpty(name)){
                redisUtil.del(
                        StringBuilderConstant.USER_MESSAGE_ + name,
                        StringBuilderConstant.USER_TOKEN_ + name,
                        StringBuilderConstant.USER_ID_ + name
                );
                log.info(name + "注销成功");

                httpServletResponse.setStatus(HttpStatus.OK.value());
                httpServletResponse.setContentType("text/json;charset=utf-8");
                httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(ResultConstant.OK));
            }
        }else{
            log.info("密匙过期");
            httpServletResponse.setStatus(HttpStatus.OK.value());
            httpServletResponse.setContentType("text/json;charset=utf-8");
            httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(ResultConstant.TOKEN_EXPIRE));
        }
        //置空
        SecurityContextHolder.getContext().setAuthentication(null);
        
    }
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return null;
        }
        log.info(token);
        //解析token.
        String userName = JwtTokenUtil.getUserNameForToken(token);
        List<Integer> roleIds = JwtTokenUtil.getRoleIdsForToken(token);
        if (userName == null || roleIds==null) {
            return null;
        }
        //过期校验
        String userTokenKey = StringBuilderConstant.USER_TOKEN_ + userName;
        boolean hasKey = redisUtil.hasKey(userTokenKey);
        if(!hasKey){
            return null;
        }

        return new UsernamePasswordAuthenticationToken(
                userName,
                null,
                myUserDetailsService.getAuthority(roleIds)
        );
    }


}
